package com.everflourish.yeah100.act.welcome;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.entity.CountryModel;
import com.everflourish.yeah100.http.LoginAndRegisterRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.UserInterruptException;

/**
 * 作者：Created by liqisi on 2016/8/3.
 * 时间：2016/8/3
 */
public class FindPasswordActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar mToolbar;
    private int mAwaitTime = 60; // 重新获取验证码需要等待60秒
    // 是否中断获取验证码倒计时
    private boolean isInterruptedCountdown = false;
    private CountryModel countryModel;
    private LoadDialog mLoadDialog;
    private TextView mVerificationCodeTv, mFindPasswordGoTv;
    private EditText mFindPasswordPhoneEt, mVerificationCodeEt, mUserPasswordEt, mPasswordConfirmEt;
    private TextInputLayout mFindPasswordPhoneTil, mVerificationCodeTil, mUserPasswordTil, mPasswordConfirmTil;
    private String mPhoneNumber;
    private LoginAndRegisterRequest mRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mRequest = LoginAndRegisterRequest.getInstance();
        countryModel = new CountryModel();
        countryModel.setName("中国");
        countryModel.setOrder("42");
        countryModel.setZone("86");
        SMSSDK.initSDK(mContext, Constant.MOB_APP_KEY, Constant.MOB_APP_SECRET);
        SMSSDK.registerEventHandler(eh);
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.find_password_toolbar);

        mFindPasswordPhoneEt = (EditText) findViewById(R.id.find_user_phone_et);
        mFindPasswordPhoneTil = (TextInputLayout) findViewById(R.id.find_user_phone_til);
        mVerificationCodeTv = (TextView) findViewById(R.id.find_verification_tv);
        mVerificationCodeEt = (EditText) findViewById(R.id.find_user_verification_et);
        mVerificationCodeTil = (TextInputLayout) findViewById(R.id.find_user_verification_til);
        mUserPasswordEt = (EditText) findViewById(R.id.find_user_password_et);
        mUserPasswordTil = (TextInputLayout) findViewById(R.id.find_user_password_til);
        mPasswordConfirmEt = (EditText) findViewById(R.id.find_password_confirm_et);
        mPasswordConfirmTil = (TextInputLayout) findViewById(R.id.find_password_confirm_til);
        mFindPasswordGoTv = (TextView) findViewById(R.id.find_password_go_tv);

        mVerificationCodeTv.setOnClickListener(this);
        mFindPasswordGoTv.setOnClickListener(this);
    }

    private void configView() {
        mToolbar.setTitle("找回密码");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
    }

    /**
     * 获取短信handler
     */
    EventHandler eh = new EventHandler() {
        @Override
        public void afterEvent(final int event, final int result, final Object data) {
            Message message = new Message();
            message.arg2 = event;
            message.arg1 = result;
            message.obj = data;
            mHandler.sendMessage(message);
        }
    };

    @SuppressLint("HandlerLeak")
    @SuppressWarnings("unchecked")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            LoadDialog.dismiss(mLoadDialog);
            int result = msg.arg1;
            int event = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    // 请求支持国家列表
//                    onCountryListGot((ArrayList<HashMap<String, Object>>) data);
                    // 匹配，封装国家列表
//                    gotoCountryListActivity();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {// 目前，手机端发送验证码已弃用。
                    // 请求验证码后，跳转到验证码填写页面
                    MyToast.showShort(mContext, "验证码已发送至你的手机");
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 目前，手机端发送验证码已弃用。
                    // 提交了验证码成功后，发送注册请求
                    // MyToast.showLong(mContext, "提交验证码成功");
                    // userPhoneRegister(mUserName, mPassword, mPhone);
                }
            } else {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE && data != null
                        && (data instanceof UserInterruptException)) {
                    // 由于此处是开发者自己决定要中断发送的，因此什么都不用做
                    return;
                }
                // 根据服务器返回的网络错误，给toast提示
                try {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;

                    JSONObject object = new JSONObject(throwable.getMessage());
                    String des = object.optString("detail");
                    String description = object.optString("description");
                    if (!TextUtils.isEmpty(des)) {
                        MyToast.showShort(mContext, des);
                        isInterruptedCountdown = true;
                        return;
                    }
                } catch (Exception e) {
                    LogUtil.e("", e);
                }
                // 如果木有找到资源，默认提示
                MyToast.showShort(mContext, "网络异常，请稍后重试");
            }
        }
    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    private void finishActivity() {
        IntentUtil.finishActivity(FindPasswordActivity.this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_verification_tv:
                getVerificationCode();
                break;
            case R.id.find_password_go_tv:
                mPhoneNumber = mFindPasswordPhoneEt.getText().toString().trim();
                if (TextUtils.isEmpty(mPhoneNumber)) {
                    mFindPasswordPhoneTil.setError("请输入手机号码");
                    return;
                } else if (!StringUtil.isPhoneNo(mPhoneNumber)) {
                    mFindPasswordPhoneTil.setError("手机号码格式有误，请重新输入");
                    return;
                } else {
                    mFindPasswordPhoneTil.setErrorEnabled(false);
                    mFindPasswordPhoneTil.setError(null);
                }
                String verificationCodeStr = mVerificationCodeEt.getText().toString().trim();
                if (TextUtils.isEmpty(verificationCodeStr)) {
                    mVerificationCodeTil.setError("请输入验证码");
                    return;
                } else {
                    mVerificationCodeTil.setErrorEnabled(false);
                    mVerificationCodeTil.setError(null);
                }
                String mUserPasswordStr = mUserPasswordEt.getText().toString().trim();
                if (TextUtils.isEmpty(mUserPasswordStr)) {
                    mUserPasswordTil.setError("请输入密码");
                    return;
                } else if (!StringUtil.isPassword(mUserPasswordStr)) {
                    mUserPasswordTil.setError("6-20位字符，支持数字和字母，区分大小写");
                    return;
                } else {
                    mUserPasswordTil.setErrorEnabled(false);
                    mUserPasswordTil.setError(null);
                }
                String mConfirmPasswordStr = mPasswordConfirmEt.getText().toString().trim();
                if (TextUtils.isEmpty(mConfirmPasswordStr)) {
                    mPasswordConfirmTil.setError("请输入确认密码");
                    return;
                } else if (!mUserPasswordStr.equals(mConfirmPasswordStr)) {
                    mPasswordConfirmTil.setError("两次输入的密码不一致");
                    return;
                } else {
                    mPasswordConfirmTil.setErrorEnabled(false);
                    mPasswordConfirmTil.setError(null);
                }
                changePasswordByPhoneRequest(mPhoneNumber, countryModel.getZone(),
                        mUserPasswordStr, verificationCodeStr);
                break;
        }
    }

    /**
     * 获取验证码倒数线程
     */
    private void getVerificationCode() {
        mPhoneNumber = mFindPasswordPhoneEt.getText().toString().trim();
        if (TextUtils.isEmpty(mPhoneNumber)) {
            mFindPasswordPhoneTil.setError("请输入手机号码");
            return;
        } else if (!StringUtil.isPhoneNo(mPhoneNumber)) {
            mFindPasswordPhoneTil.setError("手机号码格式有误，请重新输入");
            return;
        } else {
            mFindPasswordPhoneTil.setErrorEnabled(false);
            mFindPasswordPhoneTil.setError(null);
        }
        getPhoneVerificationCodeRequest(countryModel.getZone(), mPhoneNumber);
    }

    /**
     * 手机验证修改密码
     *
     * @param phoneNo
     * @param phoneZone
     * @param password
     * @param verificationCode
     */
    private void changePasswordByPhoneRequest(String phoneNo, String phoneZone,
                                              String password, String verificationCode) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...");
        JsonObjectRequest request = mRequest.changePasswordByPhoneRequest(phoneNo, phoneZone,
                password, verificationCode,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        changePasswordByPhoneListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改密码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 手机验证码修改密码监听
     *
     * @param response
     */
    private void changePasswordByPhoneListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                MyToast.showShort(mContext, "修改密码成功");
                IntentUtil.finishActivity(FindPasswordActivity.this);
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02031_000001E);
            } else if (resultCode.equals(ResultCode.result_100019E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02032_100019E);
            } else if (resultCode.equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02033_100017E);
            } else if (resultCode.equals(ResultCode.result_100007E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02034_100007E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_020399_999999E);
            } else {
                MyToast.showShort(mContext, "修改密码失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            MyToast.showShort(mContext, "修改密码失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 获取手机验证码
     *
     * @param phoneZone 区号 如：86
     * @param phoneNo   手机号码
     */
    private void getPhoneVerificationCodeRequest(String phoneZone, String phoneNo) {
        JsonObjectRequest request = mRequest.getPasswordPhoneVerificationCodeRequest(
                phoneZone, phoneNo, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        phoneVerificationCodeListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "发送验证码失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取手机验证码监听
     *
     * @param response
     */
    private void phoneVerificationCodeListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                sendPhoneMessage();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02021_000001E);
            } else if (resultCode.equals(ResultCode.result_100019E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02022_100019E);
            } else if (resultCode.equals(ResultCode.result_100017E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_02023_100017E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.login_020299_999999E);
            } else {
                MyToast.showShort(mContext, "发送验证码失败");
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
            MyToast.showShort(mContext, "发送验证码失败");
        } finally {
        }
    }

    private void sendPhoneMessage() {
//        SMSSDK.getVerificationCode(countryModel.getZone(), mPhoneNumber);
        new AsyncTask<Void, Integer, Void>() {
            @SuppressWarnings("deprecation")
            @Override
            protected void onPreExecute() {
                // 点击获取验证码后：点击无效
                mVerificationCodeTv.setClickable(false);
                isInterruptedCountdown = false;
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    for (int i = mAwaitTime; i > 0; i--) {
                        publishProgress(i);
                        Thread.sleep(1000);
                        if (isInterruptedCountdown) {
                            break;
                        }
                    }
                } catch (InterruptedException e) {
                    LogUtil.e("中断异常", e);
                }
                return null;
            }

            @SuppressWarnings("deprecation")
            @Override
            protected void onPostExecute(Void result) {
                // 执行完毕以后：按钮回复原状
                mVerificationCodeTv.setClickable(true);
                mVerificationCodeTv.setText("获取验证码");
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                int countdown = 0;
                if (values.length > 0) {
                    countdown = values[0];
                }
                mVerificationCodeTv.setText(countdown + "");
            }
        }.execute();
    }
}